import 'package:cached_video_player_plus/cached_video_player_plus.dart';
import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
      ),

      home: CacheVideoExample(),
    );
  }
}

class CacheVideoExample extends StatefulWidget {
  const CacheVideoExample({super.key});

  @override
  _CacheVideoExampleState createState() => _CacheVideoExampleState();
}

class _CacheVideoExampleState extends State<CacheVideoExample> {
  late final CachedVideoPlayerPlus _player;

  @override
  void initState() {
    super.initState();

    _player = CachedVideoPlayerPlus.networkUrl(
      Uri.parse('https://qiuniu.jinbangshichuang.com/test/20250225_211629.mp4'),
      invalidateCacheIfOlderThan: const Duration(minutes: 69), // Nice!
    );

    _player.initialize().then((_) {
      setState(() {});
      _player.controller.play();
    });
  }

  @override
  void dispose() {
    _player.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            _player.isInitialized
                ? AspectRatio(
                    aspectRatio: _player.controller.value.aspectRatio,
                    child: VideoPlayer(
                      _player.controller,
                    ), // Note: VideoPlayer from video_player package!
                  )
                : const CircularProgressIndicator.adaptive(),

            ElevatedButton(
              onPressed: () {
                _player.controller.play();
              },
              child: Text('播放'),
            ),
            ElevatedButton(
              onPressed: () {
                _player.controller.pause();
              },
              child: Text('暂停'),
            ),
          ],
        ),
      ),
    );
  }
}
